package com.cndw.kungfu.socket;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferInputStream;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import com.cndw.commons.util.BlankUtils;

import flex.messaging.io.SerializationContext;
import flex.messaging.io.amf.Amf3Input;

/**
 * 
 * 数据处理
 * 
 * @author <a href="mailto:whz-work@163.com">汪洪州</a>
 * 
 * @since 1.0 Create on 2011-5-18
 */
public class ClientHandler extends SimpleChannelUpstreamHandler {

	public static final Map<String, SocketResponse> responsies = new ConcurrentHashMap<String, SocketResponse>();

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

		ChannelBufferInputStream inputStream = new ChannelBufferInputStream((ChannelBuffer) e.getMessage());
		Amf3Input input = new Amf3Input(new SerializationContext());
		input.setInputStream(inputStream);

		SocketResponse message = (SocketResponse) input.readObject();
		SocketResponse response = responsies.remove(message.getRequestId());

		// 为空表示已放弃等待响应
		if (!BlankUtils.isBlank(response)) {
			synchronized (response) {
				response.setR(message.getR());
				response.setM(message.getM());
				response.setT(message.getT());
				response.setAction(message.getAction());
				response.setModule(message.getModule());
				response.setRequestId(message.getRequestId());
				response.setResponsed(true);
				System.out.println(message.getM());
				response.notify(); // 激活响应的等待
			}
		}
	}
}
